package com.onstar.cn.framework.mvp.base.core;

import android.content.Context;
import android.util.SparseArray;

import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.framework.network.BaseRequest;
import com.onstar.cn.framework.network.HttpInjectUtils;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.framework.network.http.CommonError;
import com.onstar.cn.framework.utils.GsonHelper;

import rx.Observable;
import rx.Subscriber;

/**
 * 处理一些外部请求，比如网络请求，本地数据库等一系列操作
 * Created by 7828wc on 2016/6/21.
 */
public abstract class BaseService<T> {
    /**
     * 处理数据，将数据提交给服务器或其他处理，同时等待服务器或其他返回结果
     *
     * @return
     */
    public Observable<T> processDatas(final RequestEntity requestEntity) {
        return Observable.create(new Observable.OnSubscribe<T>() {
            @Override
            public void call(Subscriber<? super T> subscriber) {
                try {
                    subscriber.onNext(getDatas(subscriber, requestEntity));
                } catch (Exception e) {
                    subscriber.onError(e);
                }
                subscriber.onCompleted();
            }
        });
    }


    /**
     * 处理数据，将数据提交给服务器或其他处理，同时等待服务器或其他返回结果
     *
     * @return
     */
    public Observable<T> showDatas() {
        return Observable.create(new Observable.OnSubscribe<T>() {
            @Override
            public void call(Subscriber<? super T> subscriber) {
                try {
                    subscriber.onNext(null);
                } catch (Exception e) {
                    subscriber.onError(e);
                }
                subscriber.onCompleted();
            }
        });
    }

    /**
     * 做数据请求，获取响应数据
     *
     * @return
     */
    public T getDatas(Subscriber<? super T> subscriber, RequestEntity requestEntity) {
        BaseRequest request = new BaseRequest(requestEntity != null ? requestEntity : getRequestEntity());
        SparseArray<String> reseponseData = request.excute();
        if (reseponseData != null && reseponseData.size() !=0) {
            int responseCode = -1;
            for(int i=0;i<reseponseData.size();i++) {
                responseCode = reseponseData.keyAt(i);
                break;
            }
//            for (Integer key : reseponseData.keySet()) {
//                responseCode = key;
//                break;
//            }
            if (responseCode != 200 && responseCode != 202) {
                CommonError commonError = GsonHelper.fromJson(reseponseData.get(responseCode),CommonError.class);
                subscriber.onError(new HttpException(commonError.getErrorCode(), commonError.getErrorMessage()));
            } else {
                //成功请求
                return jsonToBean(reseponseData.get(responseCode));
            }
        }
        return null;
    }


    /**
     * 做数据请求，获取响应数据
     *
     * @return
     */
    public SparseArray<String> getDatas(RequestEntity requestEntity) {
        BaseRequest request = new BaseRequest(requestEntity != null ? requestEntity : getRequestEntity());
        return request.excute();
    }
    public SparseArray<String> getDatas(RequestEntity requestEntity,Context context) {
        BaseRequest request = new BaseRequest(requestEntity != null ? requestEntity : getRequestEntity(),context);
        return request.excute();
    }
    /**
     * 做数据请求，获取响应数据
     *
     * @return
     */
    public SparseArray<Object> getDatasByByte(RequestEntity requestEntity) {
        BaseRequest request = new BaseRequest(requestEntity != null ? requestEntity : getRequestEntity());
        return request.excuteByObject();
    }


    /**
     * 生成请求Request
     *
     * @return
     */
    public abstract RequestEntity getRequestEntity();

    /**
     * 生成Response
     *
     * @param json
     * @return
     */
    public abstract T jsonToBean(String json);

    private SparseArray<String> netConnect(RequestEntity requestEntity, String methodName, Class clazz) throws HttpException {
        requestEntity = HttpInjectUtils.injectHttp(getClass(), methodName, requestEntity, clazz);
        SparseArray<String> reseponseData = getDatas(requestEntity);
        if (reseponseData != null && reseponseData.size()!=0) {
            int responseCode = -1;
//            for (Integer key : reseponseData.keySet()) {
//                responseCode = key;
//                break;
//            }
            for(int i=0;i<reseponseData.size();i++) {
                responseCode = reseponseData.keyAt(i);
                break;
            }
            if (responseCode != 200 && responseCode != 202) {
                CommonError commonError = GsonHelper.fromJson(reseponseData.get(responseCode),CommonError.class);
                throw new HttpException(commonError.getErrorCode(), commonError.getErrorMessage());
            } else {
                //成功请求
                return reseponseData;
            }
        }
        return null;
    }


//    protected String getResponse(Map<Integer, String> reseponseData) throws OnStarException {
//        if (reseponseData != null && !reseponseData.isEmpty()) {
//            int responseCode = -1;
//            for (Integer key : reseponseData.keySet()) {
//                responseCode = key;
//                break;
//            }
//            if (responseCode != 200 && responseCode != 202) {
//                CommonError commonError = JsonParseUtil.JsonToBean(CommonError.class, reseponseData.get(responseCode));
//                throw new HttpException(commonError.getErrorCode(), commonError.getErrorMessage());
//            } else {
//                return reseponseData.get(responseCode);
//            }
//        }
//        return null;
//    }
}
